package com.common.app.dialog

import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter
import com.common.app.R
import com.common.app.data.bean.WcAllCityModel
import com.common.app.data.bean.WcCityBean
import com.common.app.databinding.DialogSelectAddressBinding
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.common.base.utils.ViewUtils
import com.contrarywind.listener.OnItemSelectedListener


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：20/2/2023
 *
 * 描述：选择地区弹框
 *
 * 修订历史：
 *
 */
class SelectAddressDialog : Dialog, View.OnClickListener {
    private var binding: DialogSelectAddressBinding? = null

    /**
     *
     */
    private var mContext: Context? = null

    // 省级适配器数据
    private var provinceAdapter: ArrayWheelAdapter<*>? = null
    private var wheelListenerProvinceWv: OnItemSelectedListener? = null
    private var provinceItems = mutableListOf<WcCityBean>()
    private var provinceItem: WcCityBean? = null

    private var cityAdapter: ArrayWheelAdapter<*>? = null
    private var wheelListenerCityWv: OnItemSelectedListener? = null
    private var cityItems = mutableListOf<WcCityBean>()
    private var cityItem: WcCityBean? = null

    private var mSubscript = 0

    /**
     * 点击回调
     */
    private var listener: OnSelectAddressDialogClickListener? = null

    /**
     * 省市区三级联动
     */
    private var isThreeLevel = false
    private var isReset = false

    constructor(context: Context) : super(context, R.style.VerticalDialog) {
        mContext = context
    }

    constructor(context: Context, isThreeLevel: Boolean) : super(context, R.style.VerticalDialog) {
        mContext = context
        this.isThreeLevel = isThreeLevel
    }

    constructor(context: Context, themeResId: Int) : super(context, themeResId) {}
    protected constructor(
        context: Context,
        cancelable: Boolean,
        cancelListener: DialogInterface.OnCancelListener?
    ) : super(context, cancelable, cancelListener) {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DialogSelectAddressBinding.inflate(LayoutInflater.from(context))
        binding?.root?.let { setContentView(it) }

        binding?.let {
            it.selectCancelBtn.setOnClickListener(this)
            it.selectConfirmBtn.setOnClickListener(this)
        }
        initData()
    }

    override fun show() {
        super.show()
        //设置弹框的高为屏幕的一半宽是屏幕的宽
        val mDialogLp = this.window?.attributes

        //设置宽度
//        mDialogLp?.width = ViewGroup.LayoutParams.MATCH_PARENT
        mDialogLp?.height = (ViewUtils.getScreenHeight() * 0.4).toInt()

        mDialogLp?.gravity = Gravity.BOTTOM //设置dialog 在布局中的位置
        this.window?.attributes = mDialogLp
        window?.setWindowAnimations(R.style.bottomShowStyle) //添加动画:
        RefreshProvinceData()
    }

    private fun initData() {

        binding?.let {

            //字体样式，默认是等宽字体
            it.provinceWv.setTypeface(Typeface.SANS_SERIF)
            //设置滚轮文字大小
            it.provinceWv.setTextSize(17F)
            //设置分割线的颜色
            it.provinceWv.setDividerColor(Color.TRANSPARENT)
            // 设置分割线之间的文字的颜色
            it.provinceWv.setTextColorCenter(context.resources.getColor(R.color.text_content))
            // 设置分割线以外文字的颜色
            it.provinceWv.setTextColorOut(Color.LTGRAY)
            // 条目间距倍数
            it.provinceWv.setLineSpacingMultiplier(2.6F)
            // 绑定适配器
            provinceAdapter = ArrayWheelAdapter(provinceItems)
            it.provinceWv.adapter = provinceAdapter // 设置显示数据
            it.provinceWv.currentItem = 0 // 初始化时显示的数据
            it.provinceWv.setIsOptions(true)
            it.provinceWv.setCyclic(false)
            it.provinceWv.setItemsVisibleCount(4)


            //字体样式，默认是等宽字体
            it.cityWv.setTypeface(Typeface.SANS_SERIF)
            //设置滚轮文字大小
            it.cityWv.setTextSize(17F)
            //设置分割线的颜色
            it.cityWv.setDividerColor(Color.TRANSPARENT)
            // 设置分割线之间的文字的颜色
            it.cityWv.setTextColorCenter(context.resources.getColor(R.color.text_content))
            // 设置分割线以外文字的颜色
            it.cityWv.setTextColorOut(Color.LTGRAY)
            // 条目间距倍数
            it.cityWv.setLineSpacingMultiplier(2.6F)
            // 绑定适配器
            cityAdapter = ArrayWheelAdapter(cityItems)
            it.cityWv.adapter = cityAdapter // 设置显示数据
            it.cityWv.currentItem = 0 // 初始化时显示的数据
            it.cityWv.setIsOptions(true)
            it.cityWv.setCyclic(false)
            it.cityWv.setItemsVisibleCount(4)

            // 联动监听器
            wheelListenerProvinceWv = OnItemSelectedListener { index ->
                provinceItem = provinceItems[index]
                cityItems.clear()
                if (provinceItem?.areaList != null) {
                    cityItems.addAll(provinceItem?.areaList ?: mutableListOf())
                    binding?.cityWv?.notifyDataSetChanged()
                    binding?.cityWv?.currentItem = 0;// 初始化时显示的数据
                    cityItem = provinceItem?.areaList?.get(0)
                } else {
                    cityItem = null
                    binding?.cityWv?.notifyDataSetChanged()
                }
            }

            // 添加联动监听
            it.provinceWv.setOnItemSelectedListener(wheelListenerProvinceWv)


            // 联动监听器
            wheelListenerCityWv = OnItemSelectedListener { index ->
                if (cityItems.size > 0 && !TextUtils.isEmpty(cityItems[index].bankAreaId) && cityItems.size > index) { //只有1级联动数据
                    cityItem = cityItems[index]
                }
            }


            // 添加联动监听
            if (cityItems != null) {
                binding?.cityWv?.setOnItemSelectedListener(wheelListenerCityWv)
            }
        }

        getCountryList()
    }

    override fun onClick(v: View) {

        // 防止多次点击
        if (ViewUtils.isFastClick()) return
        binding?.let {

            if (it.selectCancelBtn === v) {
                dismiss()
            } else if (it.selectConfirmBtn === v) {
                var provinceId = ""
                var provinceName = ""
                var cityId = ""
                var cityName = ""

                provinceItem?.let {it1->
                    provinceName = it1.areaName
                    provinceId = it1.bankAreaId
                }
                cityItem?.let {it1->
                    cityName = if (it1.areaName.isNullOrEmpty()) "" else it1.areaName
                    cityId = if (it1.bankAreaId.isNullOrEmpty()) "" else it1.bankAreaId
                }
                listener?.onSuccessClick(provinceName, provinceId, mSubscript)
                listener?.onTypeNameClick(provinceName+cityName)
                dismiss()
            }
        }
    }

    /**
     * 回调接口
     */
    interface OnSelectAddressDialogClickListener {
        fun onSuccessClick(agentName: String?, provinceCode: String?, mSubscript: Int)
        fun onTypeNameClick(provinceValue: String?)
    }

    /**
     * @param listener
     */
    fun setOnSelectAddressDialogClickListener(listener: OnSelectAddressDialogClickListener?) {
        this.listener = listener
    }

    //条件选择器初始化
    private fun RefreshProvinceData() {
        binding?.let {
            isReset.yes {
                isReset = false
                it.provinceWv.notifyDataSetChanged()
                it.provinceWv.currentItem = 0 // 初始化时显示的数据

                // 请求第一个省的下级
                if (provinceItems.size > 0) {
                    provinceItem = provinceItems[0]
                }
            }

        }
    }


    //   获取国家列表
    private fun getCountryList() {
        val byMonthDataString: String = JsonUtils.getJsonForAss(context, "wcAllCityNew.json")
        JsonUtils.fromJson(byMonthDataString, WcAllCityModel::class.java)?.let {
            provinceItems.clear()
            if (!it.data.isNullOrEmpty()) {
                provinceItems.addAll(it.data)
                binding?.provinceWv?.notifyDataSetChanged()
                binding?.provinceWv?.currentItem = 0 // 初始化时显示的数据
                provinceItem = provinceItems[0]
            } else {
                provinceItem = null
                binding?.provinceWv?.notifyDataSetChanged()
            }
            if (provinceItem != null && !provinceItem?.areaList.isNullOrEmpty()) {
                cityItems.addAll(provinceItem?.areaList?: arrayListOf())
                binding?.cityWv?.notifyDataSetChanged()
                binding?.cityWv?.currentItem = 0 // 初始化时显示的数据
                cityItem = cityItems[0]
            } else {
                cityItem = null
                binding?.cityWv?.notifyDataSetChanged()
            }
//            if (cityItem != null && !cityItem?.areaList.isNullOrEmpty()) {
//                townshipItems.addAll(cityItem?.areaList?: arrayListOf())
//                township_wv.notifyDataSetChanged()
//                township_wv.setCurrentItem(0) // 初始化时显示的数据
//                townshipItem = cityItem.getAreaList().get(0)
//            } else {
//                townshipItem = null
//                township_wv.notifyDataSetChanged()
//            }
        }
    }
}
